package base

import (
	"context"
	"fmt"
	"github.com/CIPFZ/collector/internal/app"
	"github.com/CIPFZ/collector/internal/core"
	"github.com/CIPFZ/collector/internal/types"
	"github.com/CIPFZ/collector/internal/vars"
	"github.com/CIPFZ/collector/pkg/exception"
	"go.uber.org/zap"
	"os"
	"time"
)

// CollectorJob 定义 Job 接口
type CollectorJob interface {
	ID() string
	Name() string
	Type() string
	Run(ctx context.Context) error
}

// CollectorBase 负责封装任务创建和运行逻辑
type CollectorBase struct {
	manager *core.TaskManager
	logger  *zap.Logger
}

// NewCollectorBase 初始化 CollectorBase
func NewCollectorBase(collector *app.Collector) (*CollectorBase, error) {
	poolSize := collector.Config().Pool.Size
	output := collector.Config().Output.Dir
	manager, err := core.NewTaskManager(poolSize, output)
	if err != nil {
		return nil, err
	}
	return &CollectorBase{manager: manager, logger: collector.Logger()}, nil
}

// RunCollectTask 创建并运行收集任务
func (c *CollectorBase) RunCollectTask(
	ctx context.Context,
	options *types.CollectOptions,
) (*core.Task, error) {
	taskID := options.TaskID
	if taskID == "" {
		return nil, fmt.Errorf("task-id is required")
	}

	// 创建 Task
	taskCtx, cancel := context.WithCancel(ctx)
	t := &core.Task{
		ID:        taskID,
		Context:   taskCtx,
		Cancel:    cancel,
		StartTime: time.Now(),
	}

	// 根据标志创建 Job

	// 写 PID 文件
	pidFile := fmt.Sprintf(vars.TaskPIDFilePath, taskID)
	pid := os.Getpid()
	if err := os.WriteFile(pidFile, []byte(fmt.Sprintf("%d", pid)), 0644); err != nil {
		return nil, exception.NewWriteFileError(pidFile, err)
	}
	// 收集任务成功则删除PID文件
	defer func() { _ = os.Remove(pidFile) }()

	// 设置实时进度回调
	if options.Live {
		c.manager.SetProgressCallback(func(taskID string, progress float64) {
			fmt.Printf("\rTask %s progress: %.2f%%", taskID, progress)
		})
	}

	// 添加收集任务
	c.manager.AddTask(t)

	// 创建初始任务状态文件

	// 运行任务
	c.manager.RunTask(t)

	// TODO 收集完成后判断是否需要进行结果压缩

	return t, nil
}
